package com.business_clean.app.weight.dialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.business_clean.R;
import com.business_clean.app.callback.GetUrlCacheBitmapListenerWithFail;
import com.business_clean.app.uitl.DownLoadHelper;
import com.business_clean.app.uitl.DownloadUtil;
import com.business_clean.app.uitl.GlideUtil;
import com.business_clean.app.uitl.Mp4Utils;
import com.business_clean.app.uitl.ShareUtils;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.share.ShareHelperTools;
import com.business_clean.app.uitl.share.ShareParams;
import com.business_clean.app.weight.CustomPhotoView;
import com.business_clean.data.mode.ImageEntity;
import com.business_clean.data.mode.circle.ChatMessage;
import com.business_clean.ui.activity.camera.WatermarkCameraActivity;
import com.business_clean.ui.adapter.viewpager2.FragmentLazyStateAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.impl.FullScreenPopupView;
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener;
import com.lxj.xpopup.util.SmartGlideImageLoader;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.io.File;
import java.util.List;

import me.hgj.mvvmhelper.ext.LogExtKt;

/**
 * 适配工作圈的 dialog
 */
public class CustomImageViewPagerPopup extends FullScreenPopupView {

    private Context mContext;
    private String waterUrl;//当前水印链接
    private String originalUrl;//当前无水印的图片
    private boolean isHideWater = false;//是否隐藏水印
    private Bitmap mBitmapWaterDownload = null;//记录下载后的 bitmap 下次就不去下载了
    private Bitmap mBitmapNoWaterDownload = null;//记录下载后的 bitmap 下次就不去下载了

    private ImageView ivWater;//是否去除水印的图片

    private ViewPager2 viewPager2;
    private int position = 0;
    private List<ImageEntity> list;
    private ImagePagerAdapter imagePagerAdapter;

    public CustomImageViewPagerPopup(@NonNull Context context, List<ImageEntity> list) {
        super(context);
        this.mContext = context;
        this.list = list;
    }

    public CustomImageViewPagerPopup(@NonNull Context context, List<ImageEntity> list, int position) {
        super(context);
        this.mContext = context;
        this.list = list;
        this.position = position;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_image_view_pager_popup;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        ivWater = findViewById(R.id.iv_dialog_water);
        //viewpager2
        viewPager2 = findViewById(R.id.viewpager_dialog_image);
        imagePagerAdapter = new ImagePagerAdapter(list);
        viewPager2.setAdapter(imagePagerAdapter);
        viewPager2.setCurrentItem(position, false);
        //默认值 这是图片的情况
        if (list.size() > position) {
            waterUrl = list.get(position).getPhotoUrl();
            originalUrl = list.get(position).getOriginalUrl();
        }
        initObserver();
        initBindViewClick();
    }

    private void initBindViewClick() {
        //关闭 dialog
        findViewById(R.id.iv_dialog_close).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        //水印按钮
        ivWater.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isHideWater) {
                    isHideWater = true;
                } else {
                    isHideWater = false;
                }
                ivWater.setImageResource(isHideWater ? R.mipmap.icon_pre_water_false : R.mipmap.icon_pre_water_true);
                imagePagerAdapter.updateImageStatus(viewPager2.getCurrentItem(), isHideWater ? originalUrl : waterUrl);
                ToastUtil.show(isHideWater ? "已去除水印" : "已添加水印");
            }
        });

        //分享图片 or 视频
        findViewById(R.id.iv_dialog_wechat).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerBeforeBitmap(false);
            }
        });
        //保存到本地相册
        findViewById(R.id.iv_dialog_download).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                handlerBeforeBitmap(true);
            }
        });

    }

    /**
     * 监听滑动的内容
     * 1、根据滑动后的下标去拿当前的类型
     * 2、根据不同的类型模式，展示的东西不同
     */
    StandardGSYVideoPlayer videoPlayer;

    private void initObserver() {
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                waterUrl = list.get(position).getPhotoUrl();
                originalUrl = list.get(position).getOriginalUrl();
                //根据下标来判断是那种类型的
                if (2 == list.get(position).getResouceType()) {
                    ivWater.setVisibility(View.GONE);
                } else {
                    if (videoPlayer != null && videoPlayer.isInPlayingState()) {
                        videoPlayer.onVideoReset();
                    }
                    ivWater.setVisibility(View.VISIBLE);
                }
                videoPlayer = getAdapterVideoView();
                //每次切换后就清除 最好的办法是从Glide 的缓存中取，但是没有取到
                mBitmapNoWaterDownload = null;
                mBitmapWaterDownload = null;
            }
        });
    }


    private StandardGSYVideoPlayer getAdapterVideoView() {
        StandardGSYVideoPlayer itemView = (StandardGSYVideoPlayer) imagePagerAdapter.getViewByPosition(viewPager2.getCurrentItem(), R.id.video_player_dialog_preview);
        return itemView;
    }

    private Bitmap getAdapterItemImageView() {
        CustomPhotoView photoView = (CustomPhotoView) imagePagerAdapter.getViewByPosition(viewPager2.getCurrentItem(), R.id.photo_dialog_preview);
        if (photoView != null) {
            return photoView.getDownloadedBitmap(mContext, isHideWater ? originalUrl : waterUrl);
        }
        return null;
    }

    /**
     * 预览的viewPage2的 Adapter
     */
    public class ImagePagerAdapter extends BaseQuickAdapter<ImageEntity, BaseViewHolder> {


        public ImagePagerAdapter(List<ImageEntity> imageList) {
            super(R.layout.dialog_image_preview_photo, imageList);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, ImageEntity message) {
            CustomPhotoView imageView = holder.getView(R.id.photo_dialog_preview);
            StandardGSYVideoPlayer videoPlayer = holder.getView(R.id.video_player_dialog_preview);
            //设置返回键
            videoPlayer.getBackButton().setVisibility(View.GONE);
            //全屏幕
            videoPlayer.getFullscreenButton().setVisibility(View.GONE);
            ///不需要屏幕旋转
            videoPlayer.setNeedOrientationUtils(false);
            //不让滑动界面去改变进度条
            videoPlayer.setIsTouchWigetFull(false);

            //视频的方式
            if (2 == message.getResouceType()) {
                videoPlayer.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                videoPlayer.setUp(message.getVideoUrl(), true, "");
                videoPlayer.startPlayLogic();
            } else {
                videoPlayer.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                imageView.loadImage(message.getPhotoUrl());
            }
        }


        /**
         * 用来切换水印
         *
         * @param position
         * @param url
         */
        public void updateImageStatus(int position, String url) {
            getData().get(position).setPhotoUrl(url);
            notifyDataSetChanged();
        }

    }

    private void handlerBeforeBitmap(boolean whoClicked) {
        if (2 == list.get(viewPager2.getCurrentItem()).getResouceType()) {//处理视频的情况
            //下载视频 分享视频 或者保存到本地
            handlerVideo(whoClicked, list.get(viewPager2.getCurrentItem()).getVideoUrl());
        } else {
            Bitmap bitmapToHandle = isHideWater ? mBitmapNoWaterDownload : mBitmapWaterDownload;
            if (bitmapToHandle == null) {
                GlideUtil.getUrlCacheBitmapForShareThumbnail((Activity) mContext, isHideWater ? originalUrl : waterUrl, new GetUrlCacheBitmapListenerWithFail() {
                    @Override
                    public void loadBitmap(Bitmap resource) {
                        if (isHideWater) {
                            mBitmapNoWaterDownload = resource;
                        } else {
                            mBitmapWaterDownload = resource;
                        }
                        handlerBitmap(whoClicked, resource);
                    }

                    @Override
                    public void loadFail() {
                        ToastUtil.show("保存失败，请稍后再试");
                    }
                });
            } else {
                handlerBitmap(whoClicked, bitmapToHandle);
            }
        }
    }

    /**
     * 处理视频
     *
     * @param whoClicked
     * @param url        下载视频然后分享出去
     */
    private void handlerVideo(boolean whoClicked, String url) {
        DownLoadHelper.downloadFile(mContext, url, null, "video_" + System.currentTimeMillis() + ".mp4", false, new DownloadUtil.DownloadListener() {
            @Override
            public void onDownloadProgress(int progress) {

            }

            @Override
            public void onDownloadSuccess(File file) {
                if (whoClicked) { //保存到相册
                    Mp4Utils.saveVideoToAlbum(mContext, file.getAbsolutePath());
                    ToastUtil.show("成功保存到相册");
                } else { //分享
                    ShareUtils.shareWechatFriend(mContext, file);
                }
            }

            @Override
            public void onDownloadFailed(Exception e) {

            }
        });
    }

    /**
     * 处理图片
     *
     * @param b
     * @param bitmap
     */
    private void handlerBitmap(boolean b, Bitmap bitmap) {
        if (bitmap == null) {
            ToastUtil.show("图片异常");
            return;
        }
        if (b) {
            ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG);
            ToastUtil.show("保存到相册成功");
        } else {
            ShareParams params = new ShareParams();
            params.setBitmap(bitmap);
            ShareHelperTools.getInstance().shareImage(params, (Activity) mContext);
        }
    }


    @Override
    protected void onShow() {
        super.onShow();
        Log.e("tag", "CustomImageViewerPopup onShow");
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        Log.e("tag", "CustomImageViewerPopup onDismiss");
    }
}

